/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.weso.acota.dao;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.to.TagTO;
import org.weso.acota.utils.StringUtils;

/**
 *
 * @author chema
 */
public class CPVSuggestDAOImpl implements SuggestDAO {

    private String cpvUrl = "http://156.35.31.156/sparql/?default-graph-uri=http://purl.org/weso/cpv/2008&query=";


    public SuggestionTO suggest(RequestSuggestionTO request) {
    try {
            String query =
            "select distinct ?prefLabel where {"
            +"?x skos:prefLabel ?prefLabel."
            +"FILTER regex(?prefLabel, \"^"+request.getWord()+"\", \"i\")"
            + "} LIMIT 10";

            URL url = new URL(this.cpvUrl + URLEncoder.encode(query,"UTF-8")+"&format=application/json");
            System.out.println(url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "application/json");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK
                    && connection.getContentType().contains("application/json"))
             {
                InputStream is = connection.getInputStream();
                //XML
                String str = StringUtils.slurp(is);
                JSONObject json = new JSONObject(str);
                JSONObject results = json.getJSONObject("results");
                JSONArray bindings = results.getJSONArray("bindings");
                SuggestionTO suggestion = new SuggestionTO();
                List<TagTO> tags = new LinkedList<TagTO>();
                for(int i = 0; i<bindings.length();i++){
                    JSONObject result = (JSONObject)bindings.get(i);
                    JSONObject prefLabel =(JSONObject)result.get("prefLabel");
                    tags.add(new TagTO(CPVSuggestDAOImpl.class.getSimpleName(),
                            prefLabel.get("value").toString()));
                }
                suggestion.setTags(tags);
                return suggestion;
            } else {
                throw new RuntimeException("Unable to get a representation of the resource");
            }
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }

    public CPVSuggestDAOImpl() {
    }


}
